package net.easyjava.framework.web.listener;

import com.alibaba.fastjson.JSONObject;
import net.easyjava.framework.log.LogConstants;
import net.easyjava.framework.log.LogUtils;
import net.easyjava.tools.http.request.RequestTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by wxnacy on 16/7/1.
 */
public class ControllerLogListener implements ServletRequestListener {
    public static final Logger logger = LoggerFactory.getLogger(ControllerLogListener.class);
    private NamedThreadLocal<Long> startTimeThreadLocal =
            new NamedThreadLocal<Long>("StopWatch-StartTime");


    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        HttpServletRequest request = (HttpServletRequest) servletRequestEvent.getServletRequest();

        long beginTime = System.currentTimeMillis();//1、开始时间
        startTimeThreadLocal.set(beginTime);//线程绑定变量（该数据只有当前请求的线程可见）

        LogUtils.logAspectControllerBegin(request);
    }

    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {

        HttpServletRequest request = (HttpServletRequest) servletRequestEvent.getServletRequest();
        String url = RequestTools.getRealUrl(request);
        /**
         * 记录接口返回方式
         */
        Map<String,String[]> params = request.getParameterMap();
        if(params.containsKey("callback")){
            logger.info("{}\t通过jsonp格式输出数据,callback:{}", new Object[]{url, params.get("callback")[0]});
        }else {
            logger.info("{}\t通过json格式返回接口", new Object[]{url});
        }

        /**
         * 记录接口时间
         */
        long endTime = System.currentTimeMillis();//2、结束时间
        long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量（开始时间）
        long consumeTime = endTime - beginTime;//3、消耗的时间

        logger.info(LogConstants.API_TIME_SUM, new Object[]{url, consumeTime});
        LogUtils.logAspectControllerEnd(request);
    }
}
